package org.jeecgframework.web.controller;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.ValidForm;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ExceptionUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.CbsFaultCodeServiceI;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.system.pojo.base.CbsFaultCodeEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.SendMailUtil;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;



/**   
 * @Title: Controller
 * @Description: 故障代码
 * @author onlineGenerator
 * @date 2017-04-07 15:42:40
 * @version V1.0   
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsFaultCodeController")
public class CbsFaultCodeController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CbsFaultCodeController.class);

	@Autowired
	private CbsFaultCodeServiceI cbsFaultCodeService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ZyCommonService zyCommonService;
	
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 故障代码列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "cbsFaultCode")
	public ModelAndView cbsFaultCode(HttpServletRequest request) {
		return new ModelAndView("com/zybk/cbs_fault_code/cbsFaultCodeList");
	}

	/**
	 * easyui AJAX请求数据
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(CbsFaultCodeEntity cbsFaultCode,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(CbsFaultCodeEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsFaultCode, request.getParameterMap());
		try{
		//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.systemService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 故障代码新增页面跳转
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(CbsFaultCodeEntity cbsFaultCode, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(cbsFaultCode.getId())) {
			cbsFaultCode = cbsFaultCodeService.getEntity(CbsFaultCodeEntity.class, cbsFaultCode.getId());
			req.setAttribute("cbsFaultCodePage", cbsFaultCode);
		}
		return new ModelAndView("com/zybk/cbs_fault_code/cbsFaultCode-add");
	}
	

	/**
	 * 添加故障代码
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(CbsFaultCodeEntity cbsFaultCode, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "故障代码添加成功";
		try{
			cbsFaultCodeService.save(cbsFaultCode);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
			// add start 181126 Amy 邮件通知角色是barcoPM的用户
            //获取邮件地址
			List<String> listbySql = systemService.findListbySql("select email from t_s_user u LEFT JOIN t_s_role_user ru ON u.id=ru.userid LEFT JOIN t_s_role r ON ru.roleid=r.id LEFT JOIN t_s_base_user b on b.id = u.id where b.`status` = '" + Globals.User_Normal + "' and r.rolecode='" + StaticValue.RULE_CODE_BARCO_PM + "'");
			List<String> listloginemail = systemService.findListbySql("select email from t_s_user u LEFT JOIN t_s_base_user b on b.id = u.id where b.`status` = '" + Globals.User_Normal + "' and b.username='" + cbsFaultCode.getCreateBy() + "'");
            String emailTital = "CBS故障代码添加通知";
            String emailContent = "Dear 巴可项目经理：\n" +
                    "CBS系统中添加故障代码：<" + cbsFaultCode.getCode() + ">。添加人：<" + cbsFaultCode.getCreateName() + "> 。\n" +
                    "具体内容请查看http://cbs.cfg-barco.com\n" +
                    "【中影巴可客服部】\n" +
                    "* 该邮件请勿回复";
            for (int i = 0; i < listbySql.size(); i++) {
            	if (!listloginemail.get(i).toString().equals(listbySql.get(i).toString())) {
            		SendMailUtil.sendeMail(listbySql.get(i), emailTital, emailContent, systemService);
            	}
                
            }
			// add end 181126 Amy 
		}catch(Exception e){
			e.printStackTrace();
			message = "故障代码添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 故障代码编辑页面跳转
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(CbsFaultCodeEntity cbsFaultCode, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(cbsFaultCode.getId())) {
			cbsFaultCode = cbsFaultCodeService.getEntity(CbsFaultCodeEntity.class, cbsFaultCode.getId());
			req.setAttribute("cbsFaultCodePage", cbsFaultCode);
		}
		return new ModelAndView("com/zybk/cbs_fault_code/cbsFaultCode-update");
	}
	
	/**
	 * 更新故障代码
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(CbsFaultCodeEntity cbsFaultCode, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "故障代码更新成功";
		CbsFaultCodeEntity t = cbsFaultCodeService.get(CbsFaultCodeEntity.class, cbsFaultCode.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(cbsFaultCode, t);
			cbsFaultCodeService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
			// add start 181126 Amy 邮件通知角色是barcoPM的用户
            //获取邮件地址
			List<String> listbySql = systemService.findListbySql("select email from t_s_user u LEFT JOIN t_s_role_user ru ON u.id=ru.userid LEFT JOIN t_s_role r ON ru.roleid=r.id LEFT JOIN t_s_base_user b on b.id = u.id where b.`status` = '" + Globals.User_Normal + "' and r.rolecode='" + StaticValue.RULE_CODE_BARCO_PM + "'");
			List<String> listloginemail = systemService.findListbySql("select email from t_s_user u LEFT JOIN t_s_base_user b on b.id = u.id where b.`status` = '" + Globals.User_Normal + "' and b.username='" + t.getUpdateBy() + "'");
			String emailTital = "CBS故障代码更新通知";
            String emailContent = "Dear 巴可项目经理：\n" +
                    "CBS系统中故障代码：<" + t.getCode() + ">发生更新。更新人：<" + t.getUpdateName() + "> 。\n" +
                    "具体内容请查看http://cbs.cfg-barco.com\n" +
                    "【中影巴可客服部】\n" +
                    "* 该邮件请勿回复";
            for (int i = 0; i < listbySql.size(); i++) {
            	if (!listloginemail.get(i).toString().equals(listbySql.get(i).toString())) {
            		SendMailUtil.sendeMail(listbySql.get(i), emailTital, emailContent, systemService);
            	}
            }
			// add end 181126 Amy 
			
		} catch (Exception e) {
			e.printStackTrace();
			message = "故障代码更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * @author xiul
	 * 2017-4-10 下午4:37:19
	 * Description 检查故障代码唯一性
	 * @param faultCodeId 故障代码ID 更新时存在
	 */
	@ResponseBody
	@RequestMapping(params="checkFaultCodeUnique")
	public ValidForm checkFaultCodeUnique(@RequestParam(value="param",defaultValue="")String param,
			@RequestParam(value="faultCodeId",defaultValue="")String faultCodeId
			){
		ValidForm vf = new ValidForm();
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT COUNT(1) AS total ");
		sql.append(" FROM cbs_fault_code t");
		sql.append(" WHERE ");
		sql.append(" t.code = '"+param+"' ");
		if(StringUtil.isNotEmpty(faultCodeId)){
			sql.append(" AND t.id != '"+faultCodeId+"' ");
		}
		int total = zyCommonService.getCountBySql(sql.toString());
		if(total > 0){
			vf.setStatus(ValidForm.N);
			vf.setInfo("当前故障代码已经存在");
		}
		return vf;
	}
	
	/**
	 * @author xiul
	 * 2017-4-10 下午12:10:38
	 * Description 微信故障代码  - 故障查询页
	 */
	@RequestMapping(params="wxGzdmcx")
	public ModelAndView wxGzdmcx(HttpServletRequest request){
		request.setAttribute("searchCode", request.getParameter("searchCode"));
		return new ModelAndView("com/wx/self_service/gzdm/gzdmcx");
	}
	
	/**
	 * @author xiul
	 * 2017-4-10 下午2:40:47
	 * Description 微信 - 查询故障代码详细页
	 */
	@RequestMapping(params="wxGzdmcxList")
	public ModelAndView wxGzdmcxList(HttpServletRequest request){
		CbsFaultCodeEntity cbsFaultCode = cbsFaultCodeService.wxGzdmcxList(request);
		if(cbsFaultCode == null){
			String code = oConvertUtils.getString(request.getParameter("faultCode"));
			return new ModelAndView("redirect:cbsFaultCodeController.do?wxGzdmcx&searchCode=" + code);
		}
		request.setAttribute("faultCode", cbsFaultCode);
		return new ModelAndView("com/wx/self_service/gzdm/gzdmDetials");
	}
	
	/**
	 * 删除故障代码
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(CbsFaultCodeEntity cbsFaultCode, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		cbsFaultCode = systemService.getEntity(CbsFaultCodeEntity.class, cbsFaultCode.getId());
		message = "故障代码删除成功";
		try{
			cbsFaultCodeService.delete(cbsFaultCode);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "故障代码删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
}
